package com.hu.common.util.adm;


import com.hu.common.enums.MessageEnum;
import com.hu.common.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketException;
import java.util.UUID;

/**
 * UUID生成工具类
 * @author 00355760
 */
public class UUIDGeneratorUtil {
    private static final Logger logger = LoggerFactory.getLogger(UUIDGeneratorUtil.class);

    //机器ip
    private static final long WORK_ID;
    //数据中心id
    private static final long DATA_CENTER_ID;

    /**
     * 毫秒内序列(0~4095)
     */
    private static long sequence = 0L;
    /**
     * 上次生成ID的时间截
     */
    private static long lastTimestamp = -1L;


    static {
        try {
            WORK_ID = NetUtil.getHostIP();
        } catch (SocketException e) {
            logger.error("[get ip addr exception]: {}", E2s.exception2String(e));
            throw new BizException(MessageEnum.EXCEPTION.getMessage());
        }
        DATA_CENTER_ID = new Double(Math.random() * 10).longValue();
    }


    // 雪花算法
    public static synchronized long getSnowflakeId() {
        long timestamp = timeGen();

        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过
        if (timestamp < lastTimestamp) {
            logger.error("timestamp error");
           throw new BizException(MessageEnum.EXCEPTION.getMessage());
        }


        // 序列在id中占的位数
        long sequenceBits = 12L;
        if (lastTimestamp == timestamp) {

            // 生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095)
            long sequenceMask = ~(-1L << sequenceBits);
            sequence = (sequence + 1) & sequenceMask;

            // 毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        // 上次生成ID的时间截
        lastTimestamp = timestamp;

        long twepoch = 1667808312000L;

        // 机器id所占的位数
        long workerIdBits = 5L;
        long datacenterIdShift = sequenceBits + workerIdBits;

        // 数据标识id所占的位数
        long datacenterIdBits = 5L;
        long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

        // 移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift)
                | (DATA_CENTER_ID << datacenterIdShift)
                | (WORK_ID << sequenceBits)
                | sequence;
    }

    public static synchronized String getRandomId() {
        String uid = UUID.randomUUID().toString();
        String now = String.valueOf(System.currentTimeMillis());
        double random = Math.random() * 100;
        return OpenApiUtil.MD5( uid +now + random);
    }

    // 获得新的时间戳
    protected static long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }


    // 返回以毫秒为单位的当前时间
    protected static long timeGen() {
        return System.currentTimeMillis();
    }


}
